//
//  YYTransferView.m
//  Xanthium
//
//  Created by yangyongMac on 2018/7/5.
//  Copyright © 2018年 GuanQinghao. All rights reserved.
//

#import "YYTransferView.h"
#import "GQHHeader.h"
#import "TZImagePickerController.h"
#import "GQHLengthController.h"
#import "GQHModelController.h"
#import "GQHPlateController.h"

@interface YYTransferView () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, strong) NSMutableArray * titleArray;

@end

@implementation YYTransferView

- (NSMutableArray *)titleArray
{
    if (!_titleArray)
    {
        _titleArray = [NSMutableArray arrayWithObjects:@"车辆所有人", @"车牌号", @"行驶证", @"道路运输许可证", @"道路经营许可证", @"道路运输许可证号", @"挂车票照号", @"车牌类型", @"车型", @"车长", @"载重", @"车辆照片", nil];
    }
    return _titleArray;
}

- (NSMutableDictionary *)parmasDic
{
    if (!_parmasDic)
    {
        _parmasDic = [NSMutableDictionary dictionary];
    }
    return _parmasDic;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self loadUserInterface];
    }
    return self;
}


#pragma mark lazy loading...
- (void)loadUserInterface
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [self creatFooterView];
    [self addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.qh_statusBarHeight + self.qh_navigationBarHeight);
        make.left.and.right.and.bottom.mas_equalTo(self);
    }];
    
}

- (UIView *)creatFooterView
{
    UIView * footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.qh_width, 60)];
    footerView.backgroundColor = kWhiteColor;

    
    UIButton * finishButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, footerView.qh_width - 20, 40)];
    [finishButton setTitle:@"完成" forState:0];
    finishButton.backgroundColor = kAppRedColor;
    [finishButton addTarget:self action:@selector(finishAction:) forControlEvents:UIControlEventTouchUpInside];
    finishButton.layer.cornerRadius = 5;
    finishButton.layer.masksToBounds = YES;
    [footerView addSubview:finishButton];
    
    return footerView;
}

#pragma mark ------ UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 11)
    {
        return 60;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cellIdentify";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identify];
        switch (indexPath.row)
        {
            case 0:
                if (!self.textField1)
                {
                    self.textField1 = [self creatTextField:@"请输入所有人" View:cell.contentView isShow:NO];
                }
                
                break;
                
            case 1:
                if (!self.textField2)
                {
                    self.textField2 = [self creatTextField:@"请输入车牌号" View:cell.contentView isShow:NO];
                }
                
                break;
                
            case 2:
                if (!self.addImage1)
                {
                    self.addImage1 = [self creatButton:cell.contentView];
                    self.addImage2.tag = 10;
                    [self.addImage1 addTarget:self action:@selector(addImage1Action:) forControlEvents:UIControlEventTouchUpInside];
                }
                
                break;
            case 3:
                if (!self.addImage2)
                {
                    self.addImage2 = [self creatButton:cell.contentView];
                    self.addImage2.tag = 20;
                    [self.addImage2 addTarget:self action:@selector(addImage1Action:) forControlEvents:UIControlEventTouchUpInside];
                }
                
                break;
            case 4:
                self.textField3 = [self creatTextField:@"请输入道路经营许可证号" View:cell.contentView isShow:NO];
                break;
            case 5:
                self.textField4 = [self creatTextField:@"请输入道路运输许可证号" View:cell.contentView isShow:NO];
                break;
            case 6:
                self.textField5 = [self creatTextField:@"请输入挂车牌照号(选填)" View:cell.contentView isShow:NO];
                break;
            case 7:
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.detailTextLabel.text = @"请选择";
                break;
            case 8:
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.detailTextLabel.text = @"请选择";
                break;
            case 9:
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.detailTextLabel.text = @"请选择";
                break;
            case 10:
                if (!self.textField6)
                {
                    self.textField6 = [self creatTextField:@"请输入载重" View:cell.contentView isShow:YES];
                }
                
                break;
            case 11:
                if (!self.addImage3)
                {
                    [self addImage:cell.contentView];
                }
                
                break;
            default:
                break;
        }
    }
    cell.textLabel.text = self.titleArray[indexPath.row];
    
    return cell;
}

#pragma mark ------- UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 7)
    {
        /// 车牌类型
        GQHPlateController *plateController = [[GQHPlateController alloc] init];
        plateController.qh_plateBlock = ^(NSString *plateID, NSString *plateName) {
            
            [self.parmasDic setObject:plateID forKey:@"carType"];
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = plateName;
        };
        plateController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:plateController animated:YES];
    }
    else if (indexPath.row == 8)
    {
        /// 车型
        GQHModelController *modelController = [[GQHModelController alloc] init];
        modelController.qh_modelBlock = ^(NSString *modelID, NSString *modelName) {
            
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = modelName;
            [self.parmasDic setObject:modelID forKey:@"vehicleclassificationcode"];
        };
        modelController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:modelController animated:YES];
    }
    else if (indexPath.row == 9)
    {
        /// 车长
        GQHLengthController *lengthController = [[GQHLengthController alloc] init];
        lengthController.qh_lengthBlock = ^(NSString *lengthID, NSString *lengthName) {
            
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = lengthName;
            [self.parmasDic setObject:lengthID forKey:@"carLength"];
        };
        lengthController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:lengthController animated:YES];
    }
}

- (void)addImage:(UIView *)contentView
{
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(contentView.qh_width - 50, 5, 50, 50)];
    button.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    button.layer.cornerRadius = 25;
    button.layer.masksToBounds = YES;
    [contentView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.mas_equalTo(contentView).with.inset(5);
        make.right.mas_equalTo(contentView.mas_right).offset(-10);
        make.width.mas_equalTo(50);
    }];
    [button addTarget:self action:@selector(addImage1Action:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = 30;
    self.addImage3 = button;
    
    UIButton * button1 = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMinX(button.frame) - 60, 5, 50, 50)];
    button1.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    button1.layer.cornerRadius = 25;
    button1.layer.masksToBounds = YES;
    [contentView addSubview:button1];
    [button1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.mas_equalTo(contentView).with.inset(5);
        make.right.mas_equalTo(button.mas_left).offset(-10);
        make.width.mas_equalTo(50);
    }];
    button1.tag = 40;
    [button1 addTarget:self action:@selector(addImage1Action:) forControlEvents:UIControlEventTouchUpInside];
    self.addImage4 = button1;
}

- (UIButton *)creatButton:(UIView *)contentView
{
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(contentView.qh_width - 50, 5, 50, 50)];
    button.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    button.layer.cornerRadius = 25;
    button.layer.masksToBounds = YES;
    [contentView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.mas_equalTo(contentView).with.inset(5);
        make.right.mas_equalTo(contentView.mas_right).offset(-10);
        make.width.mas_equalTo(50);
    }];
    return button;
}

- (UITextField *)creatTextField:(NSString *)placeHolder View:(UIView *)contentView isShow:(BOOL)isShow
{
    CGFloat width = (contentView.qh_width - 20)  / 2;
    UITextField * textField = [[UITextField alloc] initWithFrame:CGRectMake( contentView.qh_width - width - 10, 0, width, contentView.qh_height)];
    textField.textAlignment = NSTextAlignmentRight;
    textField.placeholder = placeHolder;
    [contentView addSubview:textField];
    
    if (isShow)
    {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(contentView.qh_width - 30, 0, 20, contentView.qh_height)];
        label.text = @"吨";
        [contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.bottom.mas_equalTo(contentView).with.inset(5);
            make.right.mas_equalTo(contentView.mas_right).offset(-10);
            make.width.mas_equalTo(20);
        }];
        
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.bottom.mas_equalTo(contentView).with.inset(5);
            make.right.mas_equalTo(label.mas_left).offset(-10);
            make.width.mas_equalTo(width);
        }];
    }
    else
    {
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.and.bottom.mas_equalTo(contentView).with.inset(5);
            make.right.mas_equalTo(contentView.mas_right).offset(-10);
            make.width.mas_equalTo(width);
        }];
    }
    return textField;
}

- (void)addImage1Action:(UIButton *)sender
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(addImageAction:)])
    {
        [self.delegate addImageAction:sender];
    }
}

#pragma mark ---- 完成
- (void)finishAction:(UIButton *)sender
{
    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:7 inSection:0]];
    NSString * string = cell.detailTextLabel.text;
    
    UITableViewCell * cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:8 inSection:0]];
    NSString * string1 = cell1.detailTextLabel.text;
    
    UITableViewCell * cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:9 inSection:0]];
    NSString * string2 = cell2.detailTextLabel.text;
    
    
    if (self.textField1.text.length == 0)
    {
        [self showToastWithText:@"请输入车辆所有人"];
    }
    else if (self.textField2.text.length == 0)
    {
        [self showToastWithText:@"请输入车牌号"];
    }
    else if (self.textField3.text.length == 0)
    {
        [self showToastWithText:@"请输入道路经营许可证号"];
    }
    else if (self.textField4.text.length == 0)
    {
        [self showToastWithText:@"请输入道路运输许可证号"];
    }
    else if (self.textField6.text.length == 0)
    {
        [self showToastWithText:@"请输入载重"];
    }
    else if (!self.addImage1)
    {
        [self showToastWithText:@"请选择行驶证照片"];
    }
    else if (!self.addImage2)
    {
        [self showToastWithText:@"请选择运输许可证照片"];
    }
    else if (!self.addImage3)
    {
        [self showToastWithText:@"请选择车辆照片1"];
    }
    else if (!self.addImage4)
    {
        [self showToastWithText:@"请选择车辆照片2"];
    }
    else if (string.length == 0)
    {
        [self showToastWithText:@"请选择车牌类型"];
    }
    else if (string1.length == 0)
    {
        [self showToastWithText:@"请选择车型"];
    }
    else if (string2.length == 0)
    {
        [self showToastWithText:@"请选择车长"];
    }
    
    [self.parmasDic setObject:USER_GET_ID forKey:@"userId"];
    [self.parmasDic setObject:self.textField1.text forKey:@"carUser"];
    [self.parmasDic setObject:self.textField2.text forKey:@"licPlateNum"];
    [self.parmasDic setObject:self.textField3.text forKey:@"roadTraBuLicNum"];
    [self.parmasDic setObject:self.textField4.text forKey:@"roadTraCerNum"];
    [self.parmasDic setObject:self.textField5.text forKey:@"licPlateNum"];
    [self.parmasDic setObject:self.textField6.text forKey:@"carLoad"];
    DLog(@"换车长传参数 : %@", self.parmasDic);
    
    [self uploadInfo];
}

- (void)uploadInfo
{
    NSArray * imageArray = @[self.addImage1.currentBackgroundImage, self.addImage2.currentBackgroundImage, self.addImage3.currentBackgroundImage, self.addImage4.currentBackgroundImage];
    NSArray * titleArray = @[@"carQrivingLicPhoto",
                             @"roadTraCerLic",
                             @"CarPhoto",
                             @"CarPhoto1"];
    NSString *APIURLString = [[NSString qh_APIURLString] stringByAppendingPathComponent:@"/myInformation/1/diverAutUpdate"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [MBProgressHUD showHUDAddedTo:self animated:YES];
    [manager POST:APIURLString parameters:self.parmasDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
    {
        for (int i = 0; i < imageArray.count; i ++)
        {
            NSData *data = UIImageJPEGRepresentation(imageArray[i], 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%d.png", dateString, i];
            [formData appendPartWithFileData:data name:titleArray[i] fileName:fileName mimeType:@"image/png"];
        }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:self animated:YES];
        NSNumber *responseCode = [responseObject objectForKey:@"code"];
        NSString *responseMessage = [responseObject objectForKey:@"msg"];
        NSString *responseData = [responseObject objectForKey:@"data"];
        DLog(@"%@, %@, %@", responseCode, responseMessage, responseData);
        [self showToastWithText:@"提交成功"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self animated:YES];
        NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
        [self showToastWithText:errorString];
    }];
}

@end
